<template>
  <el-dialog
    :visible="dialogVisible"
    title="开发数据导出表清单"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="90%"
    top="5vh"
    @close="()=>{
      crud.selections = []
      crud.query = {}
      onClose()
    }"
  >
    <div class="crud-group">
      <el-input
        v-model="query.taskCode"
        clearable
        placeholder="请输入批次号"
        style="width: 11rem;"
      />
      <el-input
        v-model="query.dbName"
        clearable
        placeholder="请输入库名"
        style="width: 11rem;"
      />
      <el-input
        v-model="query.tableName"
        clearable
        placeholder="请输入表名"
        style="width: 11rem;"
      />
      <el-input
        v-model="query.errorMessage"
        clearable
        placeholder="请输入错误信息"
        style="width: 15rem;"
      />
    </div>
    <div class="crud-group">
      <el-select
        v-model="query.exportStatus"
        placeholder="请选择导出状态"
        clearable
        style="width: 11rem"
      >
        <el-option
          v-for="item in exportStatusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="query.createTimeRange"
        :default-time="['00:00:00','23:59:59']"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator=":"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 22.5rem;"
      />
      <rrOperation :crud="crud" />
      <div style="display: inline-block">
        <el-button
          slot="reference"
          v-permission="permission.restart"
          class="filter-item"
          type="primary"
          icon="el-icon-refresh"
          :loading="restartLoading"
          :disabled="crud.selections.length === 0"
          @click="toRestart(crud.selections)"
        >重跑
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          :loading="this.downLoading === true"
          icon="el-icon-download"
          @click="exportResult()"
        >导出
        </el-button>
      </div>
    </div>
    <el-table
      ref="table"
      :data="crud.data"
      border
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column
        label="导出批次"
        prop="taskCode"
        width="120px"
      />
      <el-table-column
        label="库名"
        prop="dbName"
        width="80px"
      />
      <el-table-column
        label="表名"
        prop="tableName"
      />
      <el-table-column
        label="执行AGENT"
        prop="agentKey"
      />
      <el-table-column
        label="导出状态"
        prop="exportStatusName"
      />
      <el-table-column
        label="开始时间"
        prop="startTimeString"
      />
      <el-table-column
        label="结束时间"
        prop="endTimeString"
      />
      <el-table-column
        label="耗时"
        prop="timeConsuming"
        width="180"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="toShowSql(scope.row)"
          >SQL信息
          </el-button>
          <el-button
            type="text"
            @click="toShowErrorMessage(scope.row)"
          >错误信息
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-pagination-container">
      <pagination />
    </div>

    <el-dialog
      :close-on-click-modal="false"
      title="SQL信息"
      :visible.sync="showSqlDialogVisible"
      width="800px"
      :append-to-body="true"
      top="5vh"
      :before-close="handleClose"
    >
      <show-sql
        v-if="showSqlDialogVisible"
        :sql-object="exportList"
      />
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="错误信息"
      :visible.sync="showErrorMessageVisible"
      width="1200px"
      :append-to-body="true"
      top="5vh"
      :before-close="handleClose"
    >
      <codemirror
        ref="codemirror"
        :value="errorMessage"
        :editor-height="500"
      />
    </el-dialog>
  </el-dialog>
</template>

<script>
import rrOperation from '@crud/RR.operation'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import pagination from '@crud/Pagination'
import devDataExportListApi from '@/api/dataTransfer/devDataTransfer/devDataExportList'
import showSql from './showSql'
import codemirror from '@/components/codemirror/codemirror'
import { downloadFile } from '@/utils/index'

const defaultCrud = CRUD({
  title: '',
  url: '/api/dev/data/export/list/page', crudMethod: {...devDataExportListApi}
})
const defaultForm = {}
export default {
  components: {pagination, rrOperation, showSql, codemirror},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  props: {
    dialogVisible: Boolean,
    onClose: Function,
    taskCode: String
  },
  data() {
    return {
      downLoading: false,
      restartLoading: false,
      showSqlDialogVisible: false,
      showErrorMessageVisible: false,
      errorMessage: null,
      exportList: null,
      dbName: null,
      tableName: null,
      exportStatus: null,
      exportStatusList: [
        {label: '待处理', value: 'TODO'},
        {label: '处理中', value: 'RUNNING'},
        {label: '处理成功', value: 'SUCCESS'},
        {label: '不支持', value: 'NOT_SUPPORTED'},
        {label: '已中止', value: 'ABOLISH'},
        {label: '处理失败', value: 'FAIL'}
      ],
      permission: {
        restart: ['admin', 'devExportLog:restart']
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    taskCode(val) {
      if (val) {
        this.crud.refresh()
      }
    }
  },
  methods: {
    [CRUD.HOOK.beforeRefresh](crud) {
      // crud.query.taskCode = this.taskCode
    },
    toRestart(datas) {
      this.$confirm(`确认重跑选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        if (datas instanceof Array) {
          datas.forEach(val => {
            ids.push(val.id)
          })
        } else {
          ids.push(datas.id)
        }
        this.restartLoading = true
        devDataExportListApi.restart(ids).then(res => {
          this.restartLoading = false
          this.$notify({title: '成功', message: '操作成功！', type: 'success'})
          this.crud.toQuery()
        }).catch(() => {
          this.restartLoading = false
        })
      }).catch(() => {
      })
    },
    exportResult() {
      this.downLoading = true
      const params = {
        taskCode: this.query.taskCode,
        dbName: this.query.dbName,
        tableName: this.query.tableName,
        errorMessage: this.query.errorMessage,
        exportStatus: this.query.exportStatus
      }
      if (params.taskCode === undefined) {
        params.taskCode = ''
      }
      if (params.dbName === undefined) {
        params.dbName = ''
      }
      if (params.tableName === undefined) {
        params.tableName = ''
      }
      if (params.errorMessage === undefined) {
        params.errorMessage = ''
      }
      if (params.exportStatus === undefined) {
        params.exportStatus = ''
      }
      devDataExportListApi.download(params).then(res => {
        downloadFile(res, '开发数据导出表清单', 'xls')
        this.downLoading = false
      }).catch(() => {
        this.downLoading = false
      })
    },

    toShowErrorMessage(row) {
      this.showErrorMessageVisible = true
      if (row.errorMessage !== undefined && row.errorMessage !== null && row.errorMessage !== '') {
        this.errorMessage = row.errorMessage
      } else {
        this.errorMessage = '--无任务错误信息--'
      }
    },
    toShowSql(row) {
      this.showSqlDialogVisible = true
      this.exportList = row
    },
    handleClose() {
      this.showSqlDialogVisible = false
      this.showErrorMessageVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.table-pagination-container {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
}
</style>
